﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace DSLOrder
{
    public partial class main : Form
    {
        public main()
        {
            InitializeComponent();
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer |
               ControlStyles.UserPaint |
               ControlStyles.AllPaintingInWmPaint,
               true);
            this.UpdateStyles();
        }
        Common Init = new Common();
        MsSqlHelper mssql = new MsSqlHelper();
        Api Api = new Api();
        private string _spid;
        private string json;
        JToken jToken = null;
        public string spid { get { return _spid; } set { _spid = value; } }
        DataTable dtsrc = null;
        DataTable newdt = null;

       // ExcelHelper ehelper;
        MsSqlHelper shelper;
        
        public void list(DataTable dt)
        {
            try
            {
                dGV.DataSource = dt;
               // Common.AutoSizeColumn(dGVHead);
               // Common.AutoSizeColumn(dGV);

                Common.AutoSizeColumn(dGV);

                dGV.Columns["serialNumber"].HeaderText = "serialNumber";
                dGV.Columns["serialNumber"].Visible = false;
                dGV.Columns["supplierId"].HeaderText = "供应商编码";
                dGV.Columns["supplierId"].Visible = false;
                dGV.Columns["supplierName"].HeaderText = "供应商名称";
                dGV.Columns["supplierName"].Visible = false;
                dGV.Columns["supplierItemId"].HeaderText = "商品内码";
                dGV.Columns["supplierItemName"].HeaderText = "商品名称";
                dGV.Columns["manufacturer"].HeaderText = "生产厂家";
                dGV.Columns["nationalMedicine"].HeaderText = "批准文号";
                dGV.Columns["barCode"].HeaderText = "条码";
                dGV.Columns["barCode"].Visible = false;
                dGV.Columns["subUserId"].HeaderText = "业务员ID";
                dGV.Columns["subUserId"].Visible = false;
                dGV.Columns["subUserName"].HeaderText = "业务员";
                dGV.Columns["subUserName"].Visible = false;
                dGV.Columns["userId"].HeaderText = "采购员ID";
                dGV.Columns["userId"].Visible = false;
                dGV.Columns["userName"].HeaderText = "采购员";
                dGV.Columns["itemId"].HeaderText = "商品编码";
                dGV.Columns["itemName"].HeaderText = "商品名称[大参林]";
                dGV.Columns["ypgg"].HeaderText = "规格";
                dGV.Columns["dw"].HeaderText = "单位";
                dGV.Columns["priceNeed"].HeaderText = "期望价";
                dGV.Columns["qtyNeed"].HeaderText = "需求量";
                //dGV.Columns["qtyNeed"].Visible = false;
                dGV.Columns["qtySupplierOffer"].HeaderText = "可供货数量";
                dGV.Columns["price"].HeaderText = "供货价";
                dGV.Columns["beforePrice"].HeaderText = "上次价";

                dGV.Columns["lotNumber"].HeaderText = "批号";
                dGV.Columns["productionDate"].HeaderText = "生产日期";
                dGV.Columns["validityPeriod"].HeaderText = "有效期";
                dGV.Columns["comment"].HeaderText = "备注";
                dGV.Columns["beforeComment"].HeaderText = "上次备注";
                dGV.Columns["bitCode"].HeaderText = "本位码";
                dGV.Columns["drugAdministrationSpecs"].HeaderText = "省药监规格";

                dGV.Columns["remark"].HeaderText = "价格调整摘要";
                dGV.Columns["jlgg"].HeaderText = "件装量";
                dGV.Columns["pym"].HeaderText = "拼音码";
                dGV.Columns["pym"].Visible = false;
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                MessageBox.Show("这也能出错，请重试\r\n" + ex.Message.ToString());

            }
        }
        private void dGV_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                PublicClass.Initialize();
                PublicClass.Instance.spid="";
                 
                selectsp selectsp = new selectsp();
                selectsp.Owner = this;
                string supplierItemId=dGV.Rows[e.RowIndex].Cells["supplierItemId"].Value.ToString();
                if (!string.IsNullOrEmpty(supplierItemId))
                {
                    DialogResult dialogResult = MessageBox.Show("该商品已经做了关联，是否修改？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (dialogResult != DialogResult.OK)
                    {
                        return;
                    }
                }
                selectsp.nationalMedicine = dGV.Rows[e.RowIndex].Cells["nationalMedicine"].Value.ToString();
                selectsp.manufacturer = dGV.Rows[e.RowIndex].Cells["manufacturer"].Value.ToString();
                selectsp.itemId = dGV.Rows[e.RowIndex].Cells["itemId"].Value.ToString();
                selectsp.itemName = dGV.Rows[e.RowIndex].Cells["itemName"].Value.ToString();
                selectsp.ypgg = dGV.Rows[e.RowIndex].Cells["ypgg"].Value.ToString();
                selectsp.dw = dGV.Rows[e.RowIndex].Cells["dw"].Value.ToString();
                DialogResult result = selectsp.ShowDialog();
                if (result == DialogResult.Cancel && !string.IsNullOrEmpty(PublicClass.Instance.spid))
                 {
                     spid=PublicClass.Instance.spid;
                         dGV.Rows[e.RowIndex].Cells["supplierItemId"].Value = spid;
                         dGV.Update();
                         //dGV.Sort(dGV.Columns["supplierItemName"], ListSortDirection.Ascending);
                 }
            }
        }

        private void dGV_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string nationalMedicine = dGV.Rows[dGV.CurrentCell.RowIndex].Cells["nationalMedicine"].Value.ToString();
            }
        }

        public string readStockToJson(DataTable dt)
        {
            string stockJsonStr = "";

            if (dt != null)
            {
                List<object> list = new List<object>();
                    foreach (DataRow row in dt.Rows)
                    {
                        Dictionary<string, object> dictionary = new Dictionary<string, object>();
                        foreach (DataColumn column in dt.Columns)
                        {
                            string a = column.ColumnName;
                            if (!a.Equals("remark") || !a.Equals("jlgg") || !a.Equals("pym"))
                            {
                                if (a != "remark" && a != "jlgg" && a != "pym")
                                {
                                    dictionary.Add(a, row[column]);
                                }
                            }
                        }
                        list.Add(dictionary);
                    }   
                Dictionary<string, object> dictionary2 = new Dictionary<string, object>();
                dictionary2.Add("supplierItemPriceList", list);
                stockJsonStr = JsonConvert.SerializeObject(dictionary2);
            }
            return stockJsonStr;
        }

        private void dGV_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            using (SolidBrush brush = new SolidBrush(dGV.RowHeadersDefaultCellStyle.ForeColor))
            {
                string s = (e.RowIndex + 1).ToString();
                e.Graphics.DrawString(s, e.InheritedRowStyle.Font, brush, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            About About = new About();
            About.ShowDialog();
        }

        private void 配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SysConfig SysConfig = new SysConfig();
            SysConfig.ShowDialog();
        }

        private void winFormPager1_PageChanged()
        {
            dGV.DataSource = GetList(newdt, winFormPager1.PageSize, winFormPager1.CurrentPage);
        }
        public DataTable GetList(DataTable dt, int PageSize, int CurrentPage)
        {
            DataTable newdt = dt.Copy();
            newdt.Clear();//copy dt的框架

            int rowbegin = (CurrentPage - 1) * PageSize;
            int rowend = CurrentPage * PageSize;

            if (rowbegin >= dt.Rows.Count)
                return newdt;//源数据记录数小于等于要显示的记录，直接返回dt

            if (rowend > dt.Rows.Count)
                rowend = dt.Rows.Count;
            for (int i = rowbegin; i <= rowend - 1; i++)
            {
                DataRow newdr = newdt.NewRow();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn column in dt.Columns)
                {
                    newdr[column.ColumnName] = dr[column.ColumnName];
                }
                newdt.Rows.Add(newdr);
            }
            newdt.DefaultView.Sort = "supplierItemId,supplierItemName";

            return newdt;
        }

        private void 获取ToKenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string TokenJSON = Api.GetToKen();
                JObject jObject = (JObject)JsonConvert.DeserializeObject(TokenJSON);

                string code = (string)jObject["code"];
                if (code == "200")
                {
                    Api.Token = (string)jObject["data"];
                    //MessageBox.Show("获取Token成功，可以进行获取报价单！");
                    lbinfo.Text = "获取Token成功，可以进行获取报价单！\r\n" + TokenJSON;
                }
                else
                {
                    MessageBox.Show("没有获取成功！请重试\r\n");
                }
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                MessageBox.Show("超时，请重试\r\n" + ex.Message.ToString());
            }
        }

        private void 获取报价单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string OrderJSON = Api.GetOrder();
                Init.WriteLog(OrderJSON.ToString(), true);
                JObject jObject = (JObject)JsonConvert.DeserializeObject(OrderJSON);
                string code = (string)jObject["code"];
                if (code == "200")
                {
                    jToken = jObject["data"];
                    File.WriteAllText(@"JSON.json", OrderJSON, Encoding.UTF8);
                    lbinfo.Text = "报价单获取成功！";
                    //MessageBox.Show("报价单获取成功！");

                }
                else
                {
                    MessageBox.Show("没有获取成功！请重试\r\n");
                }
            }
            catch (Exception ex)
            {                
                Init.WriteLog(ex.ToString(), true);
                MessageBox.Show("超时，请重试\r\n" + ex.Message.ToString());
            }
        }

        private void 打开JSONToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.Multiselect = true;
            openFileDialog1.Title = "请选择文件夹";
            openFileDialog1.FileName = "*.txt";
            openFileDialog1.Filter = "JSON文件(*.json)|*.json|所有文件(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filename = openFileDialog1.FileName;
                string[] contents = File.ReadAllLines(filename, Encoding.Default);
                foreach (var item in contents)
                {
                    json = item;
                }

                try
                {
                    JObject jObject = (JObject)JsonConvert.DeserializeObject(json);
                    string code = (string)jObject["code"];
                    if (code == "200")
                    {
                        jToken = jObject["data"];
                        lbinfo.Text = "读取JSON文件成功！";
                        //MessageBox.Show("读取JSON文件成功！");
                    }
                }
                catch (Exception ex)
                {
                    Init.WriteLog(ex.ToString(), true);
                    MessageBox.Show("超时，请重试\r\n" + ex.Message.ToString());
                }
            }
        }

        private void 转表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (jToken != null)
                {
                    //dtsrc.Clear();
                    //dtsrc.Columns.Clear();
                    dtsrc = new DataTable();
                    dtsrc.Columns.Add(new DataColumn("serialNumber", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("supplierId", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("supplierName", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("supplierItemId", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("supplierItemName", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("manufacturer", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("nationalMedicine", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("barCode", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("subUserId", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("subUserName", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("userId", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("userName", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("itemId", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("itemName", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("ypgg", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("dw", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("priceNeed", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("qtyNeed", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("qtySupplierOffer", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("price", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("beforePrice", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("lotNumber", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("productionDate", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("validityPeriod", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("comment", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("beforeComment", Type.GetType("System.String"))); //20190814
                    dtsrc.Columns.Add(new DataColumn("bitCode", Type.GetType("System.String"))); //20190814
                    dtsrc.Columns.Add(new DataColumn("drugAdministrationSpecs", Type.GetType("System.String")));  //20190814
                    dtsrc.Columns.Add(new DataColumn("remark", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("jlgg", Type.GetType("System.String")));
                    dtsrc.Columns.Add(new DataColumn("pym", Type.GetType("System.String")));
                    foreach (JObject item in (IEnumerable<JToken>)jToken)
                    {
                        DataRow dr = dtsrc.NewRow();
                        dr["serialNumber"] = item["serialNumber"].ToString();
                        dr["supplierId"] = item["supplierId"].ToString();
                        dr["supplierName"] = item["supplierName"].ToString();

                        string supplierItemId = mssql.GetString("select supplierItemId from [csc_user_bind_goods](nolock) where itemId='" + item["itemId"].ToString() + "'");
                        if (!string.IsNullOrEmpty(supplierItemId))
                        {
                            dr["supplierItemId"] = supplierItemId;
                        }
                        else
                        {
                            dr["supplierItemId"] = item["supplierItemId"].ToString();
                        }
                        dr["supplierItemName"] = item["supplierItemName"].ToString();
                        dr["manufacturer"] = item["manufacturer"].ToString();
                        dr["nationalMedicine"] = item["nationalMedicine"].ToString();
                        dr["barCode"] = item["barCode"].ToString();
                        dr["subUserId"] = item["subUserId"].ToString();
                        dr["subUserName"] = item["subUserName"].ToString();
                        dr["userId"] = item["userId"].ToString();
                        dr["userName"] = item["userName"].ToString();
                        dr["itemId"] = item["itemId"].ToString();
                        dr["itemName"] = item["itemName"].ToString();
                        dr["ypgg"] = item["ypgg"].ToString();
                        dr["dw"] = item["dw"].ToString();
                        dr["qtyNeed"] = item["qtyNeed"].ToString();
                        dr["qtySupplierOffer"] = item["qtySupplierOffer"].ToString();
                        dr["price"] = item["price"].ToString();
                        dr["lotNumber"] = item["lotNumber"].ToString();
                        dr["productionDate"] = item["productionDate"].ToString();
                        dr["validityPeriod"] = item["validityPeriod"].ToString();
                        dr["comment"] = item["comment"].ToString();

                        dr["priceNeed"] = item["priceNeed"].ToString();
                        dr["beforePrice"] = item["beforePrice"].ToString();
                        dr["beforeComment"] = item["beforeComment"].ToString();
                        dr["bitCode"] = item["bitCode"].ToString();
                        dr["drugAdministrationSpecs"] = item["drugAdministrationSpecs"].ToString();

                        Encoding gb2312 = Encoding.GetEncoding("GB2312");
                        dr["pym"] = Pinyin.GetInitials(dr["itemName"].ToString(), gb2312);
                        dtsrc.Rows.Add(dr);
                    }

                    newdt = new DataTable();
                    newdt.CaseSensitive = true;
                    newdt = dtsrc.Clone();
                    DataRow[] newdr = dtsrc.Select("itemName<>''");
                    for (int i = 0; i < newdr.Length; i++)
                    {
                        newdt.ImportRow((DataRow)newdr[i]);
                    }
                    winFormPager1.RecordCount = newdt.Rows.Count;
                    newdt.DefaultView.Sort = "supplierItemId,supplierItemName";
                    list(GetList(newdt, winFormPager1.PageSize, winFormPager1.CurrentPage));
                    lbinfo.Text = "转表成功！~！";
                    //MessageBox.Show("转表成功！~！");
                }
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                MessageBox.Show("转表失败，请重试\r\n" + ex.Message.ToString());
            }  
        }

        private void 标准售价ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            decimal n = Init.pricen;
            string sql = "";
            try
            {
                DataTable dt = new DataTable();
                sql = "select rtrim(通用名) as supplierItemName,case when isnull(c.price,0)<>0 then c.price when isnull(价格,0)=0 then 0 else isnull(价格,0)+(" + n + "/件装) end as price,rtrim(价格)+'_'+rtrim((" + n + "/件装)) as remark,库存 as qtySupplierOffer,rtrim(批号) as lotNumber,rtrim(效期) as validityPeriod,rtrim(生产日期) as productionDate,itemId,supplierItemId,件装 as jlgg "
                    +" from [csc_user_bind_goods] b(nolock) left join [dbo].[v_UEspkfk] a(nolock) on a.商品编号=b.supplierItemId and isnull(ptid,'')='' left join DSL_Price c(nolock) on b.supplierItemId=c.spid";
                dt = mssql.ExecuteDt(sql);
                for (int i = 0; i < dtsrc.Rows.Count; i++)
                {
                    string find = dtsrc.Rows[i]["itemId"].ToString();
                    DataRow[] dr = dt.Select("itemId = '" + find + "' ");
                    if (dr.Length > 0)
                    {
                        dtsrc.Rows[i]["supplierItemName"] = dr[0]["supplierItemName"].ToString();
                        dtsrc.Rows[i]["price"] = decimal.Round(decimal.Parse(dr[0]["price"].ToString()), 2).ToString();
                        dtsrc.Rows[i]["qtySupplierOffer"] = dr[0]["qtySupplierOffer"].ToString();
                        dtsrc.Rows[i]["lotNumber"] = dr[0]["lotNumber"].ToString();
                        dtsrc.Rows[i]["validityPeriod"] = dr[0]["validityPeriod"].ToString();
                        dtsrc.Rows[i]["productionDate"] = dr[0]["productionDate"].ToString();
                        dtsrc.Rows[i]["supplierItemId"] = dr[0]["supplierItemId"].ToString();
                        dtsrc.Rows[i]["remark"] = dr[0]["remark"].ToString();
                        dtsrc.Rows[i]["jlgg"] = dr[0]["jlgg"].ToString();
                    }
                }
                newdt = new DataTable();
                newdt = dtsrc.Clone();
                DataRow[] newdr = dtsrc.Select("supplierItemName<>''");
                for (int i = 0; i < newdr.Length; i++)
                {
                    newdt.ImportRow((DataRow)newdr[i]);
                }
                winFormPager1.RecordCount = newdt.Rows.Count;
                newdt.DefaultView.Sort = "supplierItemId,supplierItemName";             
                list(GetList(newdt, winFormPager1.PageSize, winFormPager1.CurrentPage));
                lbinfo.Text = "标准售价赋值成功！";
            }
            catch (Exception ex)
            {

                Init.WriteLog(ex.ToString(), true);
                MessageBox.Show("超时，请重试\r\n" + ex.Message.ToString());
            }
        }

        private void 控销售价ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            decimal n = Init.pricen;
            string sql = "";
            try
            {
                DataTable dt = new DataTable();
                sql = "select b.spmch+b.spmch as supplierItemName,case when isnull(c.price,0)<>0 then c.price when isnull(b.zdsj,0)=0 then 0 else isnull(b.zdsj,0)+(" + n + "/jlgg) end as price,rtrim(isnull(b.zdsj,0))+'_'+rtrim(" + n + "/jlgg) as remark,b.shl as qtySupplierOffer,rtrim(b.pihao) as lotNumber,b.sxrq as validityPeriod,b.baozhiqi as productionDate,a.itemId,a.supplierItemId,jlgg from [csc_user_bind_goods] a(nolock) left join V_Api_Goods b(nolock) on a.supplierItemId=b.spid left join DSL_Price c(nolock) on b.spid=c.spid";
                dt = mssql.ExecuteDt(sql);
                for (int i = 0; i < dtsrc.Rows.Count; i++)
                {
                    string find = dtsrc.Rows[i]["itemId"].ToString();
                    DataRow[] dr = dt.Select("itemId = '" + find + "' ");
                    if (dr.Length > 0)
                    {
                        dtsrc.Rows[i]["supplierItemName"] = dr[0]["supplierItemName"].ToString();
                        dtsrc.Rows[i]["price"] = decimal.Round(decimal.Parse(dr[0]["price"].ToString()), 2).ToString();
                        dtsrc.Rows[i]["qtySupplierOffer"] = dr[0]["qtySupplierOffer"].ToString();
                        dtsrc.Rows[i]["lotNumber"] = dr[0]["lotNumber"].ToString();
                        dtsrc.Rows[i]["validityPeriod"] = dr[0]["validityPeriod"].ToString();
                        dtsrc.Rows[i]["productionDate"] = dr[0]["productionDate"].ToString();
                        dtsrc.Rows[i]["supplierItemId"] = dr[0]["supplierItemId"].ToString();
                        dtsrc.Rows[i]["remark"] = dr[0]["remark"].ToString();
                        dtsrc.Rows[i]["jlgg"] = dr[0]["jlgg"].ToString();                        
                    }
                }
                newdt = new DataTable();
                newdt = dtsrc.Clone();
                DataRow[] newdr = dtsrc.Select("supplierItemName<>''");
                for (int i = 0; i < newdr.Length; i++)
                {
                    newdt.ImportRow((DataRow)newdr[i]);
                }
                winFormPager1.RecordCount = newdt.Rows.Count;
                newdt.DefaultView.Sort = "supplierItemId,supplierItemName";
                list(GetList(newdt, winFormPager1.PageSize, winFormPager1.CurrentPage));
                lbinfo.Text = "含控销品种售价赋值成功！";
            }
            catch (Exception ex)
            {

                Init.WriteLog(ex.ToString(), true);
                MessageBox.Show("超时，请重试\r\n" + ex.Message.ToString());
            }
        }

        private void 导出当前ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ExcelSave excelSave = new ExcelSave();
                DataTable dataTable = new DataTable();
                for (int i = 1; i < dGV.Columns.Count; i++)
                {
                    dataTable.Columns.Add(dGV.Columns[i].HeaderText);
                }
                for (int i = 0; i < dGV.Rows.Count; i++)
                {
                    DataRow dataRow = dataTable.NewRow();
                    for (int j = 1; j < dGV.Columns.Count; j++)
                    {
                        dataRow[dGV.Columns[j].HeaderText] = dGV.Rows[i].Cells[j].Value.ToString().Trim();
                    }
                    dataTable.Rows.Add(dataRow);
                }
                if (dataTable.Rows.Count > 0)
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "Excel工作簿|*.xlsx|Excel 97-2003工作薄|*.xls";
                    saveFileDialog.FileName = "导出.xls";
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        if (excelSave.CreateExcel(saveFileDialog.FileName, dataTable, "导出"))
                        {
                            lbinfo.Text = "导出当前数据成功！";
                            MessageBox.Show("导出当前数据成功！");
                        }
                        else
                        {
                            MessageBox.Show("导出失败！");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("导出失败！请先选中要导出的数据！");
                }
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                MessageBox.Show("超时，请重试\r\n" + ex.Message.ToString());
            }
        }

        private void 导出所有ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ExcelSave excelSave = new ExcelSave();
                DataTable dataTable = new DataTable();
                for (int i = 1; i < dGV.Columns.Count; i++)
                {
                    dataTable.Columns.Add(dGV.Columns[i].HeaderText);
                }
                dataTable = newdt;
                if (dataTable.Rows.Count > 0)
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "Excel工作簿|*.xlsx|Excel 97-2003工作薄|*.xls";
                    saveFileDialog.FileName = "导出.xls";
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        if (excelSave.CreateExcel(saveFileDialog.FileName, dataTable, "导出"))
                        {
                            lbinfo.Text = "导出所有数据成功！";
                            MessageBox.Show("导出所有数据成功！");
                        }
                        else
                        {
                            MessageBox.Show("导出失败！");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("导出失败！请先选中要导出的数据！");
                }
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                MessageBox.Show("超时，请重试\r\n" + ex.Message.ToString());
            }
        }

        private void 提交报价ToolStripMenuItem_Click(object sender, EventArgs e)
        {            
                string requestData = readStockToJson(newdt);
                File.WriteAllText(@"requestDataJSON.json", requestData, Encoding.UTF8);
                string result = Api.UpOrder(requestData);
                try
                {
                JObject jObject = (JObject)JsonConvert.DeserializeObject(result);
                if (jObject.Property("code") != null)
                {
                    string code = (string)jObject["code"];
                    if (code == "200")
                    {
                        lbinfo.Text = "提交报价成功！";
                        MessageBox.Show("提交报价成功!\r\n" + result);
                    }
                    else
                    {
                        MessageBox.Show("失败!\r\n" + result);
                    }
                }
                else
                {
                    Init.WriteLog(result.ToString(), false);
                    MessageBox.Show("超时，请重试\r\n" + result.ToString());
                }
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                Init.WriteLog(result.ToString(), true);
                MessageBox.Show("超时，请重试\r\n" + ex.Message.ToString());
            } 
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SysConfig SysConfig = new SysConfig();
            SysConfig.ShowDialog();
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About About = new About();
            About.ShowDialog();
        }

        private void 自动日志ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Log Log = new Log();
            Log.ShowDialog();
        }

        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                try
                {
                    if (dtsrc!=null)
                    {
                        string Search = txtSearch.Text;
                        string select = comboBox1.Text;
                        string dtselect = "";
                        newdt = new DataTable();
                        newdt = dtsrc.Clone();
                        if (select == "全部"||string.IsNullOrEmpty(select))
                        {
                            dtselect = "(supplierItemName like '%" + Search + "%' or itemName like '%" + Search + "%' or pym like '%" + Search + "%')";    
                        }
                        if (select == "未关联")
                        {
                            dtselect = "supplierItemId='' and (supplierItemName like '%" + Search + "%' or itemName like '%" + Search + "%' or pym like '%" + Search + "%')";
                        }
                        if (select == "已关联")
                        {
                            dtselect = "supplierItemId<>'' and (supplierItemName like '%" + Search + "%' or itemName like '%" + Search + "%' or pym like '%" + Search + "%')";
                        }

                        DataRow[] newdr = dtsrc.Select(dtselect, "supplierItemName desc");
                        for (int i = 0; i < newdr.Length; i++)
                        {
                            newdt.ImportRow((DataRow)newdr[i]);
                        }
                        winFormPager1.RecordCount = newdt.Rows.Count;
                        newdt.DefaultView.Sort = "supplierItemId,supplierItemName";
                        list(GetList(newdt, winFormPager1.PageSize, winFormPager1.CurrentPage));
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                    Init.WriteLog(ex.ToString(), true);
                }                
            }
        }

        private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (dtsrc != null)
            {
                string Search = txtSearch.Text;
                string select = comboBox1.Text;
                newdt = new DataTable();
                newdt = dtsrc.Clone();
                if (select == "全部")
                {
                    DataRow[] newdr = dtsrc.Select("supplierItemName like '%" + Search + "%' or itemName like '%" + Search + "%'", "supplierItemName desc");
                    for (int i = 0; i < newdr.Length; i++)
                    {
                        newdt.ImportRow((DataRow)newdr[i]);
                    }
                }
                if (select == "未关联")
                {
                    
                    DataRow[] newdr = dtsrc.Select("supplierItemId='' and (supplierItemName like '%" + Search + "%' or itemName like '%" + Search + "%')", "supplierItemName desc");
                    for (int i = 0; i < newdr.Length; i++)
                    {
                        newdt.ImportRow((DataRow)newdr[i]);
                    }
                }
                if (select == "已关联")
                {
                    DataRow[] newdr = dtsrc.Select(" supplierItemId<>'' and (supplierItemName like '%" + Search + "%' or itemName like '%" + Search + "%')", "supplierItemName desc");
                    for (int i = 0; i < newdr.Length; i++)
                    {
                        newdt.ImportRow((DataRow)newdr[i]);
                    }
                }
                winFormPager1.RecordCount = newdt.Rows.Count;
                newdt.DefaultView.Sort = "supplierItemId,supplierItemName";
                list(GetList(newdt, winFormPager1.PageSize, winFormPager1.CurrentPage));
            }
        }

        private void 最新品种ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Top Top = new Top();
                Top.ShowDialog();
        }

        private void dGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dGV.Columns[0].Index)
            {
                PublicClass.Initialize();
                PublicClass.Instance.price = "";

                FormEdit FormEdit = new FormEdit();
                FormEdit.Owner = this;
                string supplierItemId = dGV.Rows[e.RowIndex].Cells["supplierItemId"].Value.ToString();
                
                    DialogResult dialogResult = MessageBox.Show("是否修改该商品价格？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (dialogResult != DialogResult.OK)
                    {
                        return;
                    }
                    if (!string.IsNullOrEmpty(supplierItemId))
                    {
                        FormEdit.nationalMedicine = dGV.Rows[e.RowIndex].Cells["nationalMedicine"].Value.ToString();
                        FormEdit.manufacturer = dGV.Rows[e.RowIndex].Cells["manufacturer"].Value.ToString();
                        FormEdit.itemId = dGV.Rows[e.RowIndex].Cells["supplierItemId"].Value.ToString();
                        FormEdit.itemName = dGV.Rows[e.RowIndex].Cells["itemName"].Value.ToString();
                        FormEdit.ypgg = dGV.Rows[e.RowIndex].Cells["ypgg"].Value.ToString();
                        FormEdit.dw = dGV.Rows[e.RowIndex].Cells["dw"].Value.ToString();
                        FormEdit.price = dGV.Rows[e.RowIndex].Cells["price"].Value.ToString();
                        DialogResult result = FormEdit.ShowDialog();
                        if (result == DialogResult.Cancel && !string.IsNullOrEmpty(PublicClass.Instance.price))
                        {

                            dGV.Rows[e.RowIndex].Cells["price"].Value = PublicClass.Instance.price;
                            dGV.Update();
                        }
                    }
            }
            if (e.ColumnIndex == dGV.Columns[1].Index)
            {
                PublicClass.Initialize();
                PublicClass.Instance.spid = "";

                selectsp selectsp = new selectsp();
                selectsp.Owner = this;
                string supplierItemId = dGV.Rows[e.RowIndex].Cells["supplierItemId"].Value.ToString();
                if (!string.IsNullOrEmpty(supplierItemId))
                {
                    DialogResult dialogResult = MessageBox.Show("该商品已经做了关联，是否修改？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (dialogResult != DialogResult.OK)
                    {
                        return;
                    }
                }
                selectsp.supplierItemId = dGV.Rows[e.RowIndex].Cells["supplierItemId"].Value.ToString();
                selectsp.nationalMedicine = dGV.Rows[e.RowIndex].Cells["nationalMedicine"].Value.ToString();
                selectsp.manufacturer = dGV.Rows[e.RowIndex].Cells["manufacturer"].Value.ToString();
                selectsp.itemId = dGV.Rows[e.RowIndex].Cells["itemId"].Value.ToString();
                selectsp.itemName = dGV.Rows[e.RowIndex].Cells["itemName"].Value.ToString();
                selectsp.ypgg = dGV.Rows[e.RowIndex].Cells["ypgg"].Value.ToString();
                selectsp.dw = dGV.Rows[e.RowIndex].Cells["dw"].Value.ToString();
                DialogResult result = selectsp.ShowDialog();
                if (result == DialogResult.Cancel)
                {
                    spid = PublicClass.Instance.spid;
                    dGV.Rows[e.RowIndex].Cells["supplierItemId"].Value = spid;
                    dGV.Update();
                }
            }

        }

        private void 导出价格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                
                    object[,] title = { { "序号", "月份", "员工编号", "姓名", "入司时间", "部门", "身份证号码", "个人绩效", "提成", "其他工资", "水电费", "加班天数", "加班时长", "其它加班", "迟到", "早退", "上班未打卡", "下班未打卡", "事假", "病假", "年假" } };
                    string sql = "select spid,spbh,spmch,shpgg,dw,shengccj,dj, "
                        + " from [] a ";
                    sql = sql + " order by a.bmid,a.ygbh";

                    shelper = new MsSqlHelper();
                    shelper.Conn.Open();
                    MsSqlDao dao = new MsSqlDao();
                    DataTable dt = dao.FindAll(shelper.Conn, sql);

                    NPOIExportExclHelper excelHelper = new NPOIExportExclHelper();

                    MemoryStream ms = excelHelper.RenderDataTableToExcel(dt, title, "工资数据") as MemoryStream;
                    //Response.BinaryWrite(ms.ToArray());
                    ms.Close();
                    ms.Dispose();
                }            
            catch (Exception ex)
            {
               Init.WriteLog(ex.Message,true);
            }
        }

        private void 导入价格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                    string filePath = @"Down/";
                    int i = 0;
                    NPOIHelper Phelper = new NPOIHelper();
                    DataTable dt = Phelper.ExcelToTable(@filePath);

                    if (dt.Equals(null)) MessageBox.Show("dt = null");

                    foreach (DataRow item in dt.Rows)
                    {
                        //将Excel中的内容存入缓存中，一条条插入mysql数据库中
                        if (item.IsNull(0)) continue;
                        string dmsql = "delete from ExcelDao where ygbh=@p1 and month=@p0";
                        string msql = "insert into ExcelDao ()values(@p0,@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10,@p11,@p12,@p13,@p14,@p15,@p16,@p17,@p18,@p19)";
                        shelper = new MsSqlHelper();
                        shelper.Conn.Open();
                        MsSqlDao dao1 = new MsSqlDao();
                        dao1.Insert(shelper.Conn, dmsql, item, i);
                        i = dao1.Insert(shelper.Conn, msql, item, i);
                        shelper.Conn.Close();
                    }
                    if (i > 1)
                    {
                        MessageBox.Show("导入成功!");
                    }
                    else
                    {
                        MessageBox.Show("导入失败!");
                    }
                }            
            catch (Exception ex)
            {
                Init.WriteLog(ex.Message, true);
            }
        }   
    }
}
